import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';

import '../entities/article_item.dart';
import '../utils/dom_parser.dart';
import '../views/loading_container.dart';

class ArticleSearchController extends GetxController {
  static const kSearchListKey = "search_history_list";

  final list = List<ArticleItem>.empty(growable: true).obs;
  final listLoadingStatus = LoadStatus.loading.obs;
  final type = "history".obs;
  final historyList = [].val(kSearchListKey);
  final searchKey = "".obs;
  final searchFocus = FocusNode();
  final hasMore = true.obs;
  final clearText = "".obs;
  var page = 1;

  removeSearchHistory() {
    final list = historyList.val;
    list.remove(clearText.value);
    historyList.val = list;
    update();
  }

  setType(String type) {
    this.type.value = type;
  }

  search(String key) {
    searchFocus.unfocus();
    searchKey.value = key;
    if (key.isEmpty) {
      setType("history");
      return;
    }
    setType("search");
    final list = historyList.val;
    final index = list.indexOf(key);
    if (index >= 0) {
      list.removeAt(index);
    }
    list.add(key);
    historyList.val = list;
    getList();
  }

  getList({bool init = true}) async {
    if (list.isNotEmpty) {
      listLoadingStatus.value = LoadStatus.success;
    }
    var requestPage = page;
    if (!init) {
      requestPage++;
    }
    try {
      final response = await Dio().get<String>("https://fourpetal.com/page/$requestPage?s=$searchKey");
      final result = DomParser.parseArtilceList(response.data);
      hasMore.value = result.length >= 15;
      page = requestPage;
      if (init) {
        list.clear();
      }
      list.addAll(result);
    } catch(_) {
    }

    if (list.isEmpty) {
      listLoadingStatus.value = LoadStatus.empty;
    } else {
      listLoadingStatus.value = LoadStatus.success;
    }
  }

}